/*
 秒杀逻辑
 利用对象封装，模仿高级语言包
 */
var seckill = {
    // 秒杀相关的URL
    URL: {
        now: function () {
            return '/seckill/time/now';
        },
        exposer: function (seckillId) {
            return '/seckill/' + seckillId + '/exposer'
        },
        seckill: function (seckillId, md5) {
            return '/seckill/' + seckillId + '/' + md5 + '/kill'
        }
    },
    // 获得秒杀地址导出结果
    getExposer: function (seckillId) {
        var exposer;
        $.ajax({
            type : "get",
            url : seckill.URL.exposer(seckillId),
            async : false,
            success : function(result){
                exposer = result['data'];
            }
        });
        return exposer;
    },
    // 获得服务器时间
    getCurrentTimeOfRemote: function () {
        var currentTime;
        $.ajax({
            type : "get",
            url : seckill.URL.now(),
            async : false,
            success : function (result) {
                if (result && result['success']) {
                    currentTime = result['data'];
                } else {
                    console.log("获得远程服务器时间:" + result);
                }
            }
        });
        return currentTime;
    },
    // 验证电话
    validatePhone: function (phone) {
        if (phone && phone.length == 11 && !isNaN(phone)) {
            return true;
        }
        return false;
    },
    // 秒杀
    kill: function (seckillId, md5) {
        var execution;
        $.ajax({
            type : "post",
            url : seckill.URL.seckill(seckillId, md5),
            async : false,
            success : function(result){
                execution = result['data'];
            }
        });
        return execution;
    },
    // 计时器
    countdown: function (seckillId, nowTime, startTime, endTime) {
        var seckillBox = $('#seckillBox');
        if (nowTime < startTime) {
            // 秒杀未开始，倒计时效果
            var killTime = new Date(startTime + 1000);
            seckillBox.countdown(killTime, function (event) {
                // 定时消息输出
                var format = event.strftime('秒杀倒计时：%D 天 %D 天 %H 时 %M 分 %S 秒');
                seckillBox.html(format);
            }).on('finish.countdown', function () {
                window.href.reload();
            });
        } else if (nowTime > endTime) {
            // 秒杀已经结束
            seckillBox.html('秒杀已经结束');
        } else {
            // 可以秒杀, 获得暴利地址
            var exposer = seckill.getExposer(seckillId);
            if (exposer && exposer.exposed) {
                seckillBox.html('<button id="seckillButton" class="btn btn-primary btn-lg" >抢购</button>');
                $('#seckillButton').click(function (event) {
                    event.preventDefault();
                    this.disabled = true;
                    try {
                        var execution = seckill.kill(seckillId, exposer.md5);
                        if(execution) {
                            var state = execution.state;
                            switch(state) {
                                case 0:
                                    seckillBox.html("秒杀成功");
                                    break;
                                case 1:
                                    seckillBox.html("重复秒杀");
                                    break;
                                case 2:
                                    seckillBox.html("秒杀已经关闭");
                                    break;
                                case -1:
                                    seckillBox.html("内部错误");
                                    break;
                            }
                        } else {
                            alert("网络错误")
                        }
                    } finally {
                        this.disabled = false;
                    }
                });
            }
        }
    },
    // 显示弹出框
    initModal: function (modalFlag, buttonFlag) {
        // 弹出登录框
        $(modalFlag).modal({
            show: true,
            backdrop: 'static',
            keyboard: false
        });
        // 登录按钮绑定时间
        $(buttonFlag).one('click',function () {
            var killPhone = $('#killPhoneInput').val();
            // 验证电话成功
            if (seckill.validatePhone(killPhone)) {
                $.cookie('killPhone', killPhone, {expires: 7, path: '/seckill'});
                window.location.reload();
            }
            // 错误提示
            $('#killPhoneMessage').hide().html('格式错误').show(300);
        });
    },
    // 定时逻辑
    countdownLogic: function (seckillId, startTime, endTime) {
        var currentTime = seckill.getCurrentTimeOfRemote();
        if(currentTime) { // 还要判断是否是数字
            seckill.countdown(seckillId, currentTime, startTime, endTime);
        }
    },
    // 详情页秒杀逻辑
    detail: {
        init: function (parameters) {
            // 检查cookie 有没有登录
            var killPhone = $.cookie('killPhone');
            var seckillId = parameters['seckillId'];
            var startTime = parameters['startTime'];
            var endTime = parameters['endTime'];
            if (!seckill.validatePhone(killPhone)) {
                // 初始化模态窗口
                seckill.initModal('#loginModal', '#loginButton')
            } else {
                // 定时逻辑
                seckill.countdownLogic(seckillId, startTime, endTime);
            }
        }
    }
};
